﻿using System;
using System.Diagnostics;

namespace SmlEngine
{
    /// <summary>
    /// Provides an abstract base class for classes which only have one instance.
    /// </summary>
    /// <typeparam name="T">The type of Singleton.</typeparam>
    public abstract class Singleton<T> where T : class, new()
    {
        private static T instance;

        /// <summary>
        /// Gets the current instance of the specified type.
        /// </summary>
        public static T Instance
        {
            get { return instance ?? (instance = new T()); }
        }

        /// <summary>
        /// Constructs a new Singleton of the specified type.
        /// </summary>
        protected Singleton()
        {
            // Make sure we only have one instance
            Debug.Assert(instance == null,
               string.Format("Singleton of type {0} already instantiated.", typeof(T)));

            instance = this as T;

            // Validate that the cast worked
            Debug.Assert(instance != null,
               string.Format("Singleton of type {0} failed to be instantiated.", GetType()));
        }
    }
}
